package com.kingdee.eas.hr.emp.web.handler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;

import sun.misc.BASE64Encoder;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.framework.ejb.EJBFactory;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.emp.IPersonPhoto;
import com.kingdee.eas.hr.emp.PersonPhotoFactory;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.dataMapHelper.EntityMaker;
import com.kingdee.shr.dataMapHelper.MapWork;
import com.kingdee.shr.dataMapHelper.TestDataMaker;
import com.kingdee.shr.doc.DocumentFactory;
import com.kingdee.shr.doc.IDocument;
import com.kingdee.shr.entity.HRPersonal;
import com.kingdee.shr.entity.HRTransferForm4Cadre;
import com.kingdee.util.StringUtils;
import com.kingdee.util.db.SQLUtils;

/**
 * @copyright 天津金蝶软件有限公司 <br>
 *            Title: EmployeeResumeSummaryMainHandler <br>
 *            Description: 员工个人档案
 * @author yacong_liu Email:yacong_liu@kingdee.com
 * @date 2019-3-25 & 上午11:03:10
 * @since V2.0 增加导出干部任免审批表（现职）（拟任职） 功能
 */
public class EmployeeResumeSummaryMainHandler extends
		EmployeeResumeSummaryHandler {

	private IPerson iPerson = null;

	private IPersonPhoto iPersonPhoto = null;

	private Context ctx;

	public EmployeeResumeSummaryMainHandler(Context ctx) {
		this.ctx = ctx;
	}

	public EmployeeResumeSummaryMainHandler() {
		this.ctx = SHRContext.getInstance().getContext();
	}

	protected void beforeRender(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {
		super.beforeRender(request, response, modelMap);

		String operateState = getOperateStatus(request, modelMap);

		if (("readonly".equals(operateState)) || ("print".equals(operateState))) {
			modelMap.put("tagReadonly", String.valueOf(true));
		}

		boolean infoPercentVisible = !("print".equals(operateState));
		modelMap.put("infoPercentVisible", String.valueOf(infoPercentVisible));
	}

	protected void setInitData(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap,
			Map<String, Object> initData) throws SHRWebException {
		super.setInitData(request, response, modelMap, initData);
		String from = request.getParameter("from");
		if (!(StringUtils.isEmpty(from)))
			initData.put("from", from);
	}

	/**
	 * 
	 * <p>
	 * Title: downloadNowAction
	 * </p>
	 * <p>
	 * Description: 导出干部任免审批表（现职）
	 * </p>
	 * 
	 * @param req
	 * @param res
	 * @param modelMap
	 * @throws SHRWebException
	 */
	public void downloadNowAction(HttpServletRequest req,
			HttpServletResponse res, ModelMap modelMap) throws SHRWebException {

		String billId = req.getParameter("billId");
		System.out
				.println("===============downloadNowAction========billId======"
						+ billId);

		StringBuffer sb = new StringBuffer();
		sb.append(System.getProperty("EAS_HOME")).append(
				"/server/deploy/easweb.ear/shr_web.war/template");
		String templatDir = sb.toString();

		System.out.println("******************" + templatDir);

		if (!StringUtils.isEmpty(billId)) {
			String personId = billId;
			// 员工头像图片Base64码
			String imgBase = getImageBase64Code(personId);

			// fei_tong:生成 HRTransForm4Cadre实体类实例cadre
			String callChain = "导出干部任免审批表（现职）方法：";
			EntityMaker em = EntityMaker.getEntityMaker();
			TestDataMaker tdm = TestDataMaker.getTestDataMaker();
			HRTransferForm4Cadre cadre;
			// cadre = tdm.getTestCadreInstance(callChain);
			cadre = em.makeHRTransferForm4Cadre(null, personId, false,
					callChain);
			if (cadre != null) {
				cadre.setImageBase64(imgBase);

				// fei_tong:将cadre实例转化成可用的Map
				MapWork mw = MapWork.getMapWork();
				Map<String, Object> dataMap = mw.AutoMap(cadre, callChain);

				// fei_tong:调用freemarkerService方法重写res对象，并响应网络请求
				IDocument freemarker = DocumentFactory
						.produceFreemarker("template_transCadre");
				String msg = freemarker.exportDoc("干部任免审批表（现职）", dataMap, res);
				System.out.println("++++++++++______________+++++++++++++++++"
						+ msg);
			} else {
				System.out
						.println("******************导出干部任免审批（现职）失败-downloadNowAction！HRTransferForm4Cadre is Null");
			}
		}
	}

	/**
	 * 
	 * <p>
	 * Title: downloadFatureAction
	 * </p>
	 * <p>
	 * Description: 导出干部任免审批表（拟任职）
	 * </p>
	 * 
	 * @param req
	 * @param res
	 * @param modelMap
	 * @throws SHRWebException
	 */
	public void downloadFatureAction(HttpServletRequest req,
			HttpServletResponse res, ModelMap modelMap) throws SHRWebException {

		String billId = req.getParameter("billId");
		System.out
				.println("===============downloadFatureAction========billId======"
						+ billId);

		if (!StringUtils.isEmpty(billId)) {
			String personId = billId;
			// 员工头像图片Base64码
			String imgBase = getImageBase64Code(personId);

			// fei_tong:生成 HRTransForm4Cadre实体类实例cadre
			String callChain = "导出干部任免审批表（拟任职）方法：";
			EntityMaker em = EntityMaker.getEntityMaker();
			TestDataMaker tdm = TestDataMaker.getTestDataMaker();
			HRTransferForm4Cadre cadre;
			// cadre = tdm.getTestCadreInstance(callChain);
			cadre = em
					.makeHRTransferForm4Cadre(null, personId, true, callChain);
			if (cadre != null) {
				cadre.setImageBase64(imgBase);

				// fei_tong:将cadre实例转化成可用的Map
				MapWork mw = MapWork.getMapWork();
				Map<String, Object> dataMap = mw.AutoMap(cadre, callChain);

				// fei_tong:调用freemarkerService方法重写res对象，并响应网络请求
				IDocument freemarker = DocumentFactory
						.produceFreemarker("template_transCadre");
				String msg = freemarker.exportDoc("干部任免审批表（拟任职）", dataMap, res);
				System.out.println("++++++++++______________+++++++++++++++++"
						+ msg);
			} else {
				System.out
						.println("******************导出干部任免审批表（拟任职）失败—downloadFatureAction！HRTransferForm4Cadre is Null");
			}
		}

	}

	/**
	 * 导出员工基本情况word
	 * 
	 * @param req
	 * @param res
	 * @param modelMap
	 * @throws SHRWebException
	 */
	public void downloadBaseInfoAction(HttpServletRequest req,
			HttpServletResponse res, ModelMap modelMap) throws SHRWebException {

		String billId = req.getParameter("billId");
		System.out
				.println("===============downloadBaseInfoAction========billId======"
						+ billId);

		if (!StringUtils.isEmpty(billId)) {
			String personId = billId;
			// 员工头像图片Base64码
			String imgBase = getImageBase64Code(personId);
			
			// fei_tong:生成 HRTransForm4Cadre实体类实例cadre
			String callChain = "导出个人基本信息表方法：";
			EntityMaker em = EntityMaker.getEntityMaker();
//			TestDataMaker tdm = TestDataMaker.getTestDataMaker();
			HRPersonal entity;
			// cadre = tdm.getTestCadreInstance(callChain);
			entity = em
					.makeHRPersonal(null, personId, callChain);
			if (entity != null) {
				entity.setImageBase64(imgBase);

				// fei_tong:将cadre实例转化成可用的Map
				MapWork mw = MapWork.getMapWork();
				Map<String, Object> dataMap = mw.AutoMap(entity, callChain);

				// fei_tong:调用freemarkerService方法重写res对象，并响应网络请求
				IDocument freemarker = DocumentFactory
						.produceFreemarker("template_personal");
				String msg = freemarker.exportDoc("个人基本信息表", dataMap, res);
				System.out.println("++++++++++______________+++++++++++++++++"
						+ msg);
			} else {
				System.out
						.println("******************导出个人基本信息表失败—downloadFatureAction！HRTransferForm4Cadre is Null");
			}
			
		}
	}

	/**
	 * 
	 * <p>
	 * Title: getImageBase64Code
	 * </p>
	 * <p>
	 * Description: 图片Base64码
	 * </p>
	 * 
	 * @param personId
	 * @return
	 */
	private String getImageBase64Code(String personId) {

		if (StringUtils.isEmpty(personId)) {
			return "";
		}

		PersonInfo personInfo;
		HashMap personPhoto = null;
		try {
			iPerson = (iPerson != null) ? iPerson : PersonFactory
					.getRemoteInstance();
			iPersonPhoto = (iPersonPhoto != null) ? iPersonPhoto
					: PersonPhotoFactory.getRemoteInstance();

			personInfo = iPerson.getPersonInfo(new ObjectUuidPK(personId));
			// personPhoto = iPersonPhoto.getPersonPhotoData(personInfo);
			personPhoto = getPersonPhotoData(personId);
		} catch (EASBizException e) {
			System.out
					.println("*************图片Base64码—getImageBase64Code() ERROR! + personId: "
							+ personId + " Exception: " + e.toString());
		} catch (BOSException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (personPhoto != null && personPhoto.get("photofile") != null) {
			byte[] photoMage = null;
			photoMage = (byte[]) (byte[]) personPhoto.get("photofile");
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(photoMage);
		}

		return "";
	}

	/**
	 * 获取员工头像
	 * 
	 * @param personId
	 * @return
	 * @throws BOSException
	 * @throws SQLException
	 */
	private HashMap getPersonPhotoData(String personId) throws BOSException,
			SQLException {
		System.out
				.println("***********************************getPersonPhotoData");
		if (StringUtils.isEmpty(personId)) {
			return null;
		}
		HashMap map = new HashMap();
		String strSQL = "select FImageData from T_HR_PersonPhoto where FPersonID='"
				+ personId + "'";

		Connection conn = null;
		Statement statement = null;
		ResultSet rs = null;
		try {
			conn = EJBFactory.getConnection(ctx);
			statement = conn.createStatement();
			rs = statement.executeQuery(strSQL);
			while (rs.next()) {
				InputStream in = rs.getBinaryStream(1);
				int blockSize = 1024;
				byte[] block = new byte[1024];
				ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
				int len = -1;
				do {
					try {
						len = in.read(block);
					} catch (IOException e1) {
						throw new SQLException(e1.getMessage());
					}
					if (len <= 0)
						continue;
					byteOut.write(block, 0, len);
				}

				while (len == 1024);

				byte[] data = byteOut.toByteArray();

				map.put("photofile", data);
			}

		} catch (SQLException exc) {
		} finally {
			SQLUtils.cleanup(rs, statement, conn);
		}

		return map;
	}

}